package com.stony.mongo;

import com.mongodb.*;

import java.util.Map;

/**
 * Created by ShiHui on 2014/6/3.
 */

public class MongoUtil{

    public static CommandResult getServerStatus(DB db){
        if(db == null) return null;
        return db.command("serverStatus");
    }


    public static boolean ping(DB db){
        return 1 == db.command("ping").getInt("ok");
    }

    public static String getVersion(DB db){
        return getServerStatus(db).getString("version");
    }

    public static String getVersion(CommandResult cr){
        return cr.getString("version");
    }

    public static boolean isMater(Mongo mongo){
        if(mongo == null) return false;
        CommandResult cr = getServerStatus(mongo.getDB("admin"));
        if(cr.containsField("repl")) {
            Map repl = (Map) cr.get("repl");
            if(!repl.isEmpty()){
                if(repl.get("ismaster").equals(true)){
                    return true;
                }
            }
        }
        return false;
    }

}
